package cn.myframe;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import javax.jms.*;

/*******************
 *@Describe 持久化消息发送
 *@author 封神梦
 *@Time 2022/8/2
 *@Company
 ****************/
public class ActiveMQTopicCreater {
    public static void main(String[] args) {
        try {
            //创建连接工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");

            //2.创建连接
            Connection connection = connectionFactory.createConnection();

            //3.启动连接
            connection.start();

            //4.获取session(会话对象)
    /*
    arg0 是否启用事务
    arg1 消息的确认方式 自动确认
     */
            Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
            //5如主题不存在创建主题
            Topic topic = session.createTopic("first-topic");


            //6.创建一个消息的生产者对象
//    Destination destination = ;//目标对象
            MessageProducer producer = session.createProducer(topic);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            //7.创建一个消息
            for (int i = 0;i<200;i++){
                TextMessage textMessage = session.createTextMessage("欢迎来到封神空间==new==>"+i);

                //8.发送消息
                producer.send(textMessage);
                session.commit();
            }
            //9.关闭资源
            producer.close();
            session.close();
            connection.close();
        }
        catch (Exception ex){
            ex.printStackTrace();
        }

    }

    //注入属性
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Topic topic;
    @Scheduled(fixedDelay = 2000l)
    public void sendMsg(){
        jmsMessagingTemplate.convertAndSend(topic,"发送定时消息到主题");
        System.out.println("----主题消息发送成功-----");
    }
}
